<template>
	<div class="plan-lists-container">
		<!-- 清单类型选择 -->
		<div class="list-selector">
			<el-radio-group v-model="currentListType" size="small" @change="handleListTypeChange">
				<el-radio-button value="actualStart">实际开工清单</el-radio-button>
				<el-radio-button value="actualEnd">实际完工清单</el-radio-button>
				<el-radio-button value="delayStart">到时间未开工清单</el-radio-button>
				<el-radio-button value="delayEnd">到时间未完工清单</el-radio-button>
			</el-radio-group>
		</div>

		<!-- 操作栏 -->
		<div class="list-filters">
			<div class="filter-left">
				<span class="list-title">{{ getListTitle() }}</span>
				<span class="list-count">共 {{ listData.length }} 条记录</span>
			</div>
			<div class="filter-right">
				<el-dropdown :show-timeout="70" :hide-timeout="50" @command="handleExportCommand">
					<el-button type="primary" size="small" :icon="Download" :loading="exportLoading"> 导出 </el-button>
					<template #dropdown>
						<el-dropdown-menu>
							<el-dropdown-item command="select" :disabled="selectData.length == 0">导出选中</el-dropdown-item>
							<el-dropdown-item command="current">导出本页</el-dropdown-item>
							<el-dropdown-item command="all">导出全部</el-dropdown-item>
						</el-dropdown-menu>
					</template>
				</el-dropdown>
				<el-button 
					type="info" 
					size="small" 
					:icon="Refresh" 
					@click="handleRefresh"
					:loading="loading"
				>
					刷新
				</el-button>
			</div>
		</div>

		<!-- 数据表格 -->
		<div class="table-container">
			<el-table
				:data="listData"
				v-loading="loading"
				height="400"
				stripe
				border
				class="plan-table"
				:empty-text="getEmptyText()"
				style="width: 100%"
				@selection-change="(val: any[]) => { selectData = val; }"
			>
			<el-table-column type="selection" width="40" align="center" />
			<el-table-column prop="ch" label="船号" min-width="100" align="center" />
			<el-table-column prop="fd" label="分段" min-width="120" align="center" />
			<el-table-column prop="className" label="分类" min-width="100" align="center" />
			<el-table-column prop="workAreaName" label="区域" min-width="120" align="center" />
			<el-table-column prop="team" label="劳务队" min-width="120" align="center" />
			<el-table-column prop="planStart" label="计划开工" width="120" align="center">
				<template #default="{ row }">
					<span v-if="row.planStart">{{ formatDate(row.planStart) }}</span>
					<span v-else class="text-muted">-</span>
				</template>
			</el-table-column>
			<el-table-column prop="actualStart" label="实际开工" width="120" align="center">
				<template #default="{ row }">
					<span v-if="row.actualStart" :class="getDateClass(row.actualStart, row.planStart, 'start')">
						{{ formatDate(row.actualStart) }}
					</span>
					<span v-else class="text-muted">-</span>
				</template>
			</el-table-column>
			<el-table-column prop="planEnd" label="计划完工" width="120" align="center">
				<template #default="{ row }">
					<span v-if="row.planEnd">{{ formatDate(row.planEnd) }}</span>
					<span v-else class="text-muted">-</span>
				</template>
			</el-table-column>
			<el-table-column prop="actualEnd" label="实际完工" width="120" align="center">
				<template #default="{ row }">
					<span v-if="row.actualEnd" :class="getDateClass(row.actualEnd, row.planEnd, 'end')">
						{{ formatDate(row.actualEnd) }}
					</span>
					<span v-else class="text-muted">-</span>
				</template>
			</el-table-column>
			</el-table>
		</div>

		<!-- 分页 -->
		<div class="pagination-container">
			<el-pagination
				v-model:current-page="pagination.currentPage"
				v-model:page-size="pagination.pageSize"
				:page-sizes="[10, 20, 50, 100, 200]"
				:total="pagination.total"
				layout="total, sizes, prev, pager, next, jumper"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			/>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { Download, Refresh } from '@element-plus/icons-vue';
import { downloadStreamFile } from '/@/utils/download';
import { usePlanViewApi } from '/@/api/plans/planView';

interface PlanListItem {
	ch: string;
	fd: string;
	className: string;
	workAreaName: string;
	team: string;
	planStart?: string;
	actualStart?: string;
	planEnd?: string;
	actualEnd?: string;
}

interface Props {
	queryParams: any;
}

const props = defineProps<Props>();
const planViewApi = usePlanViewApi();

// 响应式数据
const currentListType = ref<string>('actualStart');
const listData = ref<PlanListItem[]>([]);
const loading = ref(false);
const exportLoading = ref(false);
const selectData = ref<PlanListItem[]>([]);

const pagination = reactive({
	currentPage: 1,
	pageSize: 10,
	total: 0
});

// 清单类型配置
const listTypeConfig = {
	actualStart: { title: '实际开工清单', desc: '已实际开工的计划清单' },
	actualEnd: { title: '实际完工清单', desc: '已实际完工的计划清单' },
	delayStart: { title: '到时间未开工清单', desc: '计划开工时间已到但未开工的清单' },
	delayEnd: { title: '到时间未完工清单', desc: '计划完工时间已到但未完工的清单' }
};

// 获取清单标题
const getListTitle = () => {
	return listTypeConfig[currentListType.value as keyof typeof listTypeConfig]?.title || '清单';
};

// 获取空数据提示
const getEmptyText = () => {
	const config = listTypeConfig[currentListType.value as keyof typeof listTypeConfig];
	return loading.value ? '加载中...' : `暂无${config?.title || ''}数据`;
};

// 格式化日期
const formatDate = (dateStr: string) => {
	if (!dateStr) return '-';
	return new Date(dateStr).toLocaleDateString('zh-CN');
};

// 获取日期样式类
const getDateClass = (actualDate: string, planDate: string, type: 'start' | 'end') => {
	if (!actualDate || !planDate) return '';
	
	const actual = new Date(actualDate);
	const plan = new Date(planDate);
	
	if (actual <= plan) {
		return 'text-success'; // 按时或提前
	} else {
		return 'text-danger'; // 延期
	}
};

// 加载清单数据
const loadListData = async () => {
	if (!props.queryParams.workTime) {
		ElMessage.warning('请先选择查询月份');
		return;
	}

	loading.value = true;
	try {
    const computeBusinessRange = (workTime?: string) => {
        // 若上层传入了显式范围，则直接使用
        if (props.queryParams?.rangeStart && props.queryParams?.rangeEnd) {
            return { rangeStart: props.queryParams.rangeStart, rangeEnd: props.queryParams.rangeEnd } as any;
        }
        if (!workTime) return {} as any;
        const [y, m] = workTime.split('-').map((s: string) => parseInt(s, 10));
        if (!y || !m) return {} as any;
        const pad = (n: number) => String(n).padStart(2, '0');
        const fmt = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${String(d.getMilliseconds()).padStart(3,'0')}`;
        const target = new Date(y, m - 1, 1);
        const prev = new Date(y, m - 2, 1);
        const start = new Date(prev.getFullYear(), prev.getMonth(), 26, 0, 0, 0, 0);
        const end = new Date(target.getFullYear(), target.getMonth(), 25, 23, 59, 59, 999);
        return { rangeStart: fmt(start), rangeEnd: fmt(end) };
    };

    const params = {
        ...props.queryParams,
        ...computeBusinessRange(props.queryParams?.workTime),
        listType: currentListType.value,
        pageIndex: pagination.currentPage,
        pageSize: pagination.pageSize
    };

		// 调用API获取清单数据
		const response = await planViewApi.getPlanLists(params);
		if (response?.data?.result) {
			listData.value = response.data.result.items || [];
			pagination.total = response.data.result.total || 0;
		} else {
			listData.value = [];
			pagination.total = 0;
		}
	} catch (error) {
		console.error('加载清单数据失败:', error);
		ElMessage.error('加载清单数据失败');
		listData.value = [];
		pagination.total = 0;
	} finally {
		loading.value = false;
	}
};

// 清单类型切换
const handleListTypeChange = () => {
	pagination.currentPage = 1;
	loadListData();
};

// 刷新数据
const handleRefresh = () => {
	loadListData();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
	pagination.pageSize = size;
	pagination.currentPage = 1;
	loadListData();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
	pagination.currentPage = page;
	loadListData();
};

// 导出Excel - 统一导出方法
const handleExportCommand = async (command: string) => {
	try {
		exportLoading.value = true;
		
		// 基础参数
        const baseParams = {
            ...props.queryParams,
            ...computeBusinessRange(props.queryParams?.workTime),
            listType: currentListType.value
        };
		
		let params: any;
		if (command === 'select') {
			// 导出选中 - 添加选中的记录ID列表
			params = Object.assign({}, baseParams, { 
				selectKeyList: selectData.value.map((u: any) => u.id) 
			});
		} else if (command === 'current') {
			// 导出本页 - 添加分页参数
			params = Object.assign({}, baseParams, {
				pageIndex: pagination.currentPage,
				pageSize: pagination.pageSize
			});
		} else if (command === 'all') {
			// 导出全部 - 设置最大页码
			params = Object.assign({}, baseParams, { 
				pageIndex: 1, 
				pageSize: 99999999 
			});
		}

		console.log('导出计划清单Excel参数:', params);
		const response = await planViewApi.exportPlanListsExcel(params);
		await downloadStreamFile(response);
	} catch (error) {
		console.error('导出失败:', error);
		ElMessage.error('导出失败');
	} finally {
		exportLoading.value = false;
	}
};

// 组件挂载时加载数据
onMounted(() => {
	if (props.queryParams.workTime) {
		loadListData();
	}
});

// 暴露方法给父组件
defineExpose({
	refresh: loadListData
});
</script>

<style lang="scss" scoped>
.plan-lists-container {
	width: 100%;
	padding: 20px;
	
	.list-selector {
		margin-bottom: 16px;
		padding: 16px;
		background: var(--el-bg-color-page);
		border-radius: 4px;
		border: 1px solid var(--el-border-color-light);
	}

	.list-filters {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 16px;
		padding: 12px;
		background-color: #f8f9fa;
		border-radius: 4px;

		.filter-left {
			flex: 1;
			display: flex;
			align-items: center;
			gap: 12px;

			.list-title {
				font-size: 16px;
				font-weight: 600;
				color: var(--el-text-color-primary);
			}

			.list-count {
				font-size: 14px;
				color: var(--el-text-color-regular);
				background: var(--el-color-info-light-9);
				padding: 4px 8px;
				border-radius: 4px;
			}
		}

		.filter-right {
			margin-left: 16px;
			display: flex;
			gap: 8px;
		}
	}

	.table-container {
		.plan-table {
			:deep(.el-table__header) {
				background-color: #fafafa;
			}

			:deep(.el-table__row) {
				&:hover {
					background-color: #f5f7fa;
				}
			}
		}
	}

	.pagination-container {
		display: flex;
		justify-content: center;
		margin-top: 20px;
	}

	// 表格样式
	:deep(.el-table) {
		.text-success {
			color: var(--el-color-success);
			font-weight: 500;
		}

		.text-danger {
			color: var(--el-color-danger);
			font-weight: 500;
		}

		.text-muted {
			color: var(--el-text-color-placeholder);
		}
	}
}

@media (max-width: 768px) {
	.plan-lists-container {
		padding: 15px;

		.list-selector {
			padding: 12px;
		}

		.list-filters {
			.filter-left {
				gap: 8px;

				.list-title {
					font-size: 14px;
				}

				.list-count {
					font-size: 12px;
					padding: 2px 6px;
				}
			}

			.filter-right {
				gap: 6px;
			}
		}

		.plan-table {
			:deep(.el-table__body-wrapper) {
				overflow-x: auto;
			}
		}
	}
}
</style>
